其他
Java 中如何优雅的实现对外接口,需要注意哪些事项?
>>号外:关注“Java精选”公众号,回复“2021面试题”,领取免费资料!“Java精选面试题”小程序,3000+ 道面试题在线刷,最新、最全 Java 面试题!
做接口需要考虑的问题
package com.caiex.vb.model;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Result", propOrder = { "resultCode", "resultMsg" })
public class Result implements Serializable {
private static final long serialVersionUID = 10L;
protected int resultCode;
protected String resultMsg;
public int getResultCode() {
return this.resultCode;
}
public void setResultCode(int value) {
this.resultCode = value;
}
public String getResultMsg() {
return this.resultMsg;
}
public void setResultMsg(String value) {
this.resultMsg = value;
}
}
package com.caiex.vb.model;
import java.io.Serializable;
public class Response implements Serializable {
private static final long serialVersionUID = 2360867989280235575L;
private Result result;
private Object data;
public Result getResult() {
if (this.result == null) {
this.result = new Result();
}
return result;
}
public void setResult(Result result) {
this.result = result;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
public static int NO_AGENT_RATE = 1119; //未找到兑换率
public static int SCHEME_COMMIT_FAIL = 4000; //方案提交失败
public static int SCHEME_CONFIRMATION = 4001; //方案确认中
public static int SCHEME_NOT_EXIST = 4002; //方案不存在
public static int SCHEME_CANCEL= 4005; //方案不存在
//。。。。
package com.caiex.vb.interceptor;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.caiex.vb.model.Response;
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 所有异常报错
* @param request
* @param exception
* @return
* @throws Exception
*/
@ExceptionHandler(value=Exception.class)
public Response allExceptionHandler(HttpServletRequest request,
Exception exception) throws Exception
{
logger.error("拦截到异常:", exception);
Response response = new Response();
response.setData(null);
response.getResult().setResultCode(9999);
response.getResult().setResultMsg("系统繁忙");
return response;
}
}
package com.caiex.vb.interceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.caiex.redis.service.api.RedisApi;
import com.caiex.vb.model.Response;
import com.caiex.vb.utils.CaiexCheckUtils;
@Component
public class SignInterceptor extends BaseValidator implements HandlerInterceptor{
private Logger logger = LogManager.getLogger(this.getClass());
@Resource
private RedisApi redisApi;
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
// TODO Auto-generated method stub
}
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception {
if(isTestIpAddr(arg0)){
return true;
}
String securityKey = redisApi.hGet("securityKey", arg0.getParameter("agentid"));
if(StringUtils.isEmpty(securityKey)){
Response response = new Response();
response.setData(null);
response.getResult().setResultCode(8001);
response.getResult().setResultMsg("缺少私钥, 渠道号:" + arg0.getParameter("agentid"));
logger.error("缺少私钥, 渠道号:" + arg0.getParameter("agentid"));
InterceptorResp.printJson(arg1, response);
return false;
}
if(StringUtils.isEmpty(arg0.getParameter("sign")) || !arg0.getParameter("sign").equals(CaiexCheckUtils.getSign(arg0.getParameterMap(), securityKey))){
Response response = new Response();
response.setData(null);
response.getResult().setResultCode(3203);
response.getResult().setResultMsg("参数签名认证失败");
logger.error("参数签名认证失败:" + JSON.toJSONString(arg0.getParameterMap()) + " securityKey = " + securityKey);
InterceptorResp.printJson(arg1, response);
return false;
}else{
return true;
}
}
}
package com.caiex.oltp.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.caiex.oltp.interceptor.APILimitRateValidator;
import com.caiex.oltp.interceptor.CommonValidator;
import com.caiex.oltp.interceptor.DDSAuthValidator;
import com.caiex.oltp.interceptor.QueryPriceParamsValidator;
import com.caiex.oltp.interceptor.TradeParamsValidator;
@EnableWebMvc
@Configuration
@ComponentScan
public class WebAppConfigurer extends WebMvcConfigurerAdapter {
@Bean
CommonValidator commonInterceptor() {
return new CommonValidator();
}
@Bean
DDSAuthValidator ddsAuthInterceptor() {
return new DDSAuthValidator();
}
@Bean
QueryPriceParamsValidator queryPriceParamsInterceptor() {
return new QueryPriceParamsValidator();
}
@Bean
TradeParamsValidator tradeParamsInterceptor() {
return new TradeParamsValidator();
}
@Bean
APILimitRateValidator aPILimitRateInterceptor() {
return new APILimitRateValidator();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//访问速率限制
registry.addInterceptor(aPILimitRateInterceptor())
.addPathPatterns("/*/*");
//.addPathPatterns("/price/getPriceParam");
//参数签名认证
registry.addInterceptor(ddsAuthInterceptor())
.addPathPatterns("/tradeState/*")
.addPathPatterns("/recycle/*")
.addPathPatterns("/matchInfo/*")
.addPathPatterns("/price/tradeTicketParam");
//公共参数检查
registry.addInterceptor(commonInterceptor())
.addPathPatterns("/price/tradeTicketParam")
.addPathPatterns("/tradeState/*")
.addPathPatterns("/recycle/*");
//询价参数校验
registry.addInterceptor(queryPriceParamsInterceptor())
.addPathPatterns("/price/getPriceParam");
//交易参数检查
registry.addInterceptor(tradeParamsInterceptor())
.addPathPatterns("/price/tradeTicketParam");
super.addInterceptors(registry);
}
}
private String createToken(){
String utk = "Msk!D*"+System.currentTimeMillis()+"UBR&FLP";
logger.info("create token --- "+Md5Util.md5(utk));
return Md5Util.md5(utk);
}
轮询 | 默认方式 |
weight | 权重方式 |
ip_hash | 依据ip分配方式 |
least_conn | 最少连接方式 |
fair(第三方) | 响应时间方式 |
url_hash(第三方) | 依据URL分配方式 |
作者:xiaolizh
blog.csdn.net/xiaolizh/article/details/83011031
Spring Boot 框架中如何使用 AOP 防止重复提交?(附源码)
Google 出品 Java 编码风格规范,强烈推荐,权威又科学!
Spring Cloud 项目中实现推送消息到 RabbitMQ 消息中间件
程序员网站 Stack Overflow 被收购!以后“抄代码”难道要付费了?
为什么阿里规范需要在 @Transactional 事务注解中指定 rollbackFor?
拒绝 kill -9 强制停止,如何优雅停止 Spring Boot 服务?
数据库连接池到底应该设置多大?响应时间从 100ms 优化到 3ms!
IntelliJ IDEA 中使用热部署 JRebel 神器,开发效率提升一倍!